package com.example.Servlet;

import com.example.Pojo.Book;
import com.example.Pojo.Member;
import com.example.Pojo.User;
import com.example.dao.impl.OperationDaoImpl;
import com.example.dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BookProject extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        //反射
        String action = req.getParameter("action");

        try {
            Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void book(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
        String username = req.getParameter("username");
        String telephone = req.getParameter("telephone");
        String project = req.getParameter("project");
        String booktime = req.getParameter("booktime");
        Book book = new Book();
        book.setProject(project);
        book.setUsername(username);
        book.setTelephone(telephone);
        book.setBooktime(booktime);
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
        /*只有vip客户可以预约，而member对象表示的就是vip客户*/
        String op = username+"预约了"+booktime+"的"+project+"项目";
        Member member = new UserDaoImpl().getMember(telephone);
        if (new OperationDaoImpl().saveBookProject(book) > 0 && new UserDaoImpl().insertOperation(member,op,date) > 0 ){
            if (new OperationDaoImpl().countOperation() >14 && new OperationDaoImpl().deleteOne() >0){
                System.out.println("预约成功!");
            }else {
                System.out.println("预约成功，但数据处理异常");
            }
        }else {
            System.out.println("操作失误，请重试!");
        }
    }

    public void cancel(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
        String telephone = req.getParameter("telephone");
        if(new OperationDaoImpl().deleteBook(telephone) > 0 ){
            System.out.println("取消预约---success");
        }else {
            System.out.println("取消预约遇到了异常~");
        }
    }
}
